package com.dajiba.demo

import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter

class ViewPagerAdapter(
    fragmentManager: FragmentManager,
    private var tabNames: ArrayList<String>?,
    private var fragmentList: ArrayList<Fragment>?,
    behavior: Int = BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT
) : FragmentPagerAdapter(fragmentManager, behavior) {

    fun getFragments(): ArrayList<Fragment>? {
        return fragmentList
    }

    override fun getItem(position: Int): Fragment {
        return fragmentList!![position]
    }

    override fun getCount(): Int {
        return fragmentList!!.size
    }

    override fun getItemPosition(page: Any): Int {
        if (page is Fragment) {
            val index = fragmentList?.indexOf(page)
            return if (index == -1) {
                POSITION_NONE
            } else {
                index!!
            }
        }
        return super.getItemPosition(page)
    }

    override fun getItemId(position: Int): Long {
        return fragmentList!![position].hashCode().toLong()
    }

    override fun getPageTitle(position: Int): CharSequence? {
        if (tabNames == null) {
            return null
        }
        return tabNames!![position]
    }
}